var ws = require("nodejs-websocket");

var wsServer;
var jsonArr = [];
var frameIdx = 0;

function main() {
    createWsServer(7373)

    //每50ms广播一次驱动
    setInterval(() => {
        var emptyFrame = {
            Id:frameIdx,
            Type:0,
            FrameData:null
        }
        var msg = JSON.stringify(emptyFrame);
        if(jsonArr.length > 0){
            msg =jsonArr[0];
            jsonArr.splice(0,1);
            console.log(`广播： ${msg}`)
        }

        serverBroadcast(msg);
    }, 50);

}

function createWsServer(port) {
    console.log(`创建本地websocket,port:  ${port}`);
    //websocket
    wsServer = ws.createServer(conn => {
        console.log("一个客户端连接了,当前连接数:", wsServer.connections.length);
        conn.on('error', err => {
            console.log("client error:", err);
        });
        conn.on('close', msg => {
            console.log("一个客户端断开了连接,当前连接数:", wsServer.connections.length);
        });
        conn.on('text', function (result) {
            jsonArr.push(result);
        })

    }).listen(port);

    wsServer.on('error', err => {
        console.log("server error: ", err);
    });

}

function serverBroadcast(data) {

    // console.log("========================MSG===========================\n")
    // console.log(data);
    // console.log("===================================================\n")

    if (typeof data == 'string') {
        serverBroadcastJson(data);
    } else if (data instanceof Uint8Array) {
        serverBroadcastBinary(data);
    } else {
        console.log('未设置转发数据类型: ', data);
    }
}

function serverBroadcastJson(json) {
    wsServer.connections.forEach(conn => {
        conn.send(json);
    });
}

function serverBroadcastBinary(binary) {
    wsServer.connections.forEach(conn => {
        conn.sendBinary(binary);
    });
}

function closeServer() {
    console.log("server close");
    wsServer.close();
    onCloseProcess();
}

main();
